package com.haizhi.workstation.web.controller;

import com.haizhi.workstation.annotation.AccessLimit;
import com.haizhi.workstation.mq.AppOperationMessage;
import com.haizhi.workstation.mq.MQSender;
import com.haizhi.workstation.result.Result;
import com.haizhi.workstation.util.Constants;
import com.haizhi.workstation.util.HttpClientUtils;
import com.haizhi.workstation.util.JSONUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 公安网的中间层应用
 */
//@Api(tags="公安网的中间层应用Controller")
@RestController
@Slf4j
//@RequestMapping("public")
public class PublicSecurityController {
    @Autowired
    private MQSender mqSender;
    @Autowired
    private Constants constants;

    @Value("${public.dataFileUrlPrefix}")
    private String dataFileUrlPrefix;
    @Value("${public.dataShitfSize}")
    private int dataShitfSize;
//    @Autowired
//    private RedisServer redisServer;
    //本地标记  当处理请求数量达到限制,标记不再处理新请求
    //public static ConcurrentHashMap<String,Boolean> localSign = new ConcurrentHashMap<>();

    @ApiOperation(value="公安网访问图像网的接口", notes="公安网去访问图像网的通道接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appId", value = "业务系统唯一标识", required = false, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "requestUrl", value = "公安网端去请求的url(图像网端应用提供的服务接口)", required = true, dataType = "String",paramType = "query"),
            //@ApiImplicitParam(name = "responseUrl", value = "公安网端响应url", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "data", value = "请求携带的图片等二进制形式的数据", required = false, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "params", value = "请求参数数组params", required = true, dataType = "String[]",paramType = "query")
    })
    @RequestMapping(value = "toImage", method = RequestMethod.POST)
    @AccessLimit(seconds = 1,maxCount = 10)
    public Result<String> toImage(HttpServletRequest request){
//        String responseUrl = request.getRemoteAddr()/*+":"+request.getRemotePort()*/;
        String responseUrl = request.getParameter("responseUrl");
        String requestUrl = request.getParameter("requestUrl");
        String filename = requestUrl.replace(":","-").replace("/","-")+"-"+new Date().getTime();
        String appId = request.getParameter("appId");
        if(StringUtils.hasLength(appId)){
            filename = appId+"-"+filename;
        }
        AppOperationMessage appOperationMessage = new AppOperationMessage();

        appOperationMessage.setRequestUrl(request.getParameter("requestUrl"));

        //appOperationMessage.setKey(request.getParameter("key"));
        String data = request.getParameter("data");
        if(StringUtils.hasLength(data) && data.length()>dataShitfSize){//如果data参数过长则自动保存到文件中  message中存放的是文件路径
            String uuid = UUID.randomUUID().toString();
            JSONUtil.saveDataToFile(dataFileUrlPrefix+uuid,data);
            appOperationMessage.setDataFileUrlOrData(dataFileUrlPrefix+uuid+".json");
        }else{
            appOperationMessage.setDataFileUrlOrData(request.getParameter("data"));
        }
        log.info("DataFileUrlOrData:{}",appOperationMessage.getDataFileUrlOrData());



        appOperationMessage.setParams(request.getParameter("params"));
        appOperationMessage.setResponseUrl(responseUrl);
        appOperationMessage.setDataUrl(filename);
        mqSender.sendAppOperation(appOperationMessage);
        //每当请求处理结束,增加redis中接受请求的数量
        //redisServer.incr(Constants.REQUEST_COUNT_KEY);
        return Result.success(null);
    }

    /**
     * 测试
     * @param request
     * @return
     */
    @RequestMapping(value = "/hello",method = RequestMethod.POST)
    public String hello(HttpServletRequest request){
        System.out.println("========HELLO!!!=========");
        String header = request.getHeader("Content-Type");
        System.out.println(header);
        System.out.println("data:"+request.getParameter("data"));
        System.out.println("params:"+request.getParameter("params"));
        return "========HELLO!!!=========";
    }

    /**
     *
     * @param fileName
     * @param fileContent
     * @return
     */
    @ApiOperation(value="勿用，仅供程序使用", notes="公安网接收图像网发送的文件")
    @RequestMapping(value = "/receiveFileFromImage",method = RequestMethod.POST)
    public void receiveFileFromImage(String fileName,String fileContent){
        JSONUtil.saveDataToFile(constants.PUBLIC_RECEIVE_FOLDER+fileName,fileContent);
        log.info("=====fileName====={}",fileName);

    }
}
